﻿using System;
using System.Collections.Generic;
using log4net;
using log4net.Config;
using System.IO;

namespace NormalGsearch
{
    class NormalGSearchController
    {
        private GoogleAuthenticationProxy googleAuthentication;
        private GoogleTrendsProxy googleTrends;
        private GoogleSearchProxy googleSearch;
        private NormalGSearchViewModel viewModel;
        private ILog logger;

        private static string LogConfigFileName = "normalGSearchLogCfg.xml";

        public NormalGSearchController(NormalGSearchViewModel viewModel)
        {
            Initialize();
            logger.Info("Started normalGsearch");

            this.viewModel = viewModel;

            viewModel.OnRequestStartSearch += HandleStartSearchRequested;

            googleAuthentication = new GoogleAuthenticationProxy(viewModel);
            googleTrends = new GoogleTrendsProxy(viewModel, googleAuthentication);
            googleSearch = new GoogleSearchProxy(viewModel, googleAuthentication);
        }

        private void Initialize()
        {
            string fullExecutablePath = typeof(NormalGSearchController).Assembly.Location;
            string executablePath = Path.GetDirectoryName(fullExecutablePath);

            string logConfigFilePath = executablePath + @"\Config\" + LogConfigFileName;

            if (File.Exists(logConfigFilePath))
            {
                XmlConfigurator.Configure(new FileInfo(logConfigFilePath));
            }

            logger = LogManager.GetLogger(typeof(NormalGSearchController));

            logger.Debug("Initialized logger");
        }

        private void HandleStartSearchRequested(object sender, EventArgs e)
        {
            logger.Debug("Authenticating at Google ...");
            if (googleAuthentication.Authenticate())
            {                
                List<string> searchTerms = googleTrends.GetSearchTerms();

                if (searchTerms.Count > 0)
                    googleSearch.TriggerSearches(searchTerms);
                else
                    logger.Error("");
            }
        }
    }
}
